package com.example.demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Demo {

    public static String sendPostRequest(String urlString, String jsonData) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authorization","Bearer 504ffa15-e46d-4a41-bfe1-71f42d219255");

            // 允许输出
            connection.setDoOutput(true);

            // 发送JSON数据
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonData.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应
            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return response.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static final int TOTAL_TASKS = 100000;

    private static final int BATCH_COUNT = 16;

    private static final int BATCH_SIZE = TOTAL_TASKS / BATCH_COUNT;

    private static final  int baseNum=43509;

    public static void main(String[] args) {

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(BATCH_COUNT);

        List<Future<List<String>>> futures = new ArrayList<>();

        long startTime = System.currentTimeMillis();

        // 提交8个批次的任务
        for (int i = 0; i < BATCH_COUNT; i++) {
            int start = i * BATCH_SIZE;
            int end = (i == BATCH_COUNT - 1) ? TOTAL_TASKS : (i + 1) * BATCH_SIZE;

            Future<List<String>> future = executor.submit(new BatchTask(i, start, end));
            futures.add(future);
        }

        // 收集结果
        List<String> allResults = new ArrayList<>();
        for (Future<List<String>> future : futures) {
            try {
                allResults.addAll(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        long endTime = System.currentTimeMillis();

        System.out.println("所有任务完成！总结果数: " + allResults.size());
        System.out.println("总耗时: " + (endTime - startTime) + "ms");

        // 关闭线程池
        executor.shutdown();

    }


    static class BatchTask implements Callable<List<String>> {
        private final int batchId;
        private final int start;
        private final int end;

        public BatchTask(int batchId, int start, int end) {
            this.batchId = batchId;
            this.start = start;
            this.end = end;
        }

        @Override
        public List<String> call() {
            List<String> results = new ArrayList<>();
            System.out.println("批次 " + batchId + " 开始处理: " + start + " - " + end);

            int num=start+baseNum;
            int endNum=end+baseNum;
            String url = "http://127.0.0.1:8106/user/register/hash";

            for (int i = num; i < endNum; i++) {
                String jsonData = "{\n" +
                        "    \"username\": \"user_"+i+"\",\n" +
                        "    \"password\": \"123456\"\n" +
                        "}";

                String response = sendPostRequest(url, jsonData);
                System.out.println(i+"Response: " + response);
                results.add(response);
            }


            System.out.println("批次 " + batchId + " 完成，处理了 " + (end - start) + " 个任务");
            return results;
        }


    }
}
